
new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        name: '算法导论',
        price: 109,
        date: '2001 - 9',
        count: 1,
      },
      {
        id: 1,
        name: '编程珠玑',
        price: 99,
        date: '2003 - 9',
        count: 1,
      },
      {
        id: 1,
        name: '代码大全',
        price: 129,
        date: '2007 - 9',
        count: 1,
      }, {
        id: 1,
        name: 'Unix编程艺术',
        price: 89,
        date: '2004 - 9',
        count: 1,
      }]
  },
  methods: {
    add(index) {
      this.books[index].count++
    },
    sub(index) {
      this.books[index].count--
    },
    removeRow(index) {
      this.books.splice(index, 1)
    }
  },
  computed: {
    totalPrice() {
      //let totol = 0;
      // for (let i = 0; i < this.books.length; i++) {
      //   totol += this.books[i].price * this.books[i].count
      // }
      // return totol

      // 其他形式的for循环
      // for (i in this.books) {
      //   // 拿到的是索引值
      //   totol += this.books[i].price * this.books[i].count
      // }
      // return totol

      // // 直接拿到数组中元素
      // for (item of this.books)
      //   totol += item.price * item.count
      // return totol

      return this.books.reduce((preValue, item) =>
        totol = preValue + item.price * item.count
        , 0)

    }
  },
  filters: {
    showPrice(price) {
      return '￥' + price.toFixed(2)
    }
  }
})
